<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="路线名称" prop="routeName">
        <el-input
          v-model="queryParams.routeName"
          placeholder="请输入路线名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="站点名称" prop="siteName">
        <el-input
          v-model="queryParams.siteName"
          placeholder="请输入站点名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="phonenumber">
        <el-input
          v-model="queryParams.phonenumber"
          placeholder="请输入手机号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户名" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入用户名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="车牌号" prop="busNumber">
        <el-input
          v-model="queryParams.busNumber"
          placeholder="请输入车牌号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="路线状态" prop="routeStatus">
        <el-select v-model="queryParams.routeStatus" placeholder="请选择路线状态" clearable size="small">
          <el-option
            v-for="dict in routeStatusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['bus:route:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['bus:route:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['bus:route:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['bus:route:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleAllExport"
        >导出所有站点数据</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="routeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"  sortable/>
      <!--<el-table-column label="路线主键" align="center" prop="routeId" />-->
      <el-table-column label="名称" align="center" prop="routeName"  sortable/>
      <el-table-column label="司机" align="center" prop="userName"  sortable/>
      <el-table-column label="手机号" align="center" prop="phonenumber"  sortable/>
      <el-table-column label="车牌号" align="center" prop="busNumber"  sortable/>
      <el-table-column label="总长度" align="center" prop="routeTotalLength"  sortable/>
      <el-table-column label="总时长" align="center" prop="routeTotalTime"  sortable/>
      <el-table-column label="站点总数" align="center" prop="routeTotalSite"  sortable/>
      <el-table-column label="路线状态" align="center" prop="routeStatus" :formatter="routeStatusFormat"  sortable/>
      <el-table-column label="周末预约" align="center" prop="appointHoliday" :formatter="appointHolidayFormat"  sortable/>
      <el-table-column label="早班发车时间" align="center" prop="startAmTime" sortable/>
      <el-table-column label="晚班发车时间" align="center" prop="startPmTime" sortable/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['bus:route:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['bus:route:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleManage(scope.row)"
            v-hasPermi="['bus:route:remove']"
          >站点管理</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改路线对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="routeName">
          <el-input v-model="form.routeName" placeholder="请输入路线名称" />
        </el-form-item>
        <el-form-item label="总长度" prop="routeTotalLength">
          <el-input v-model="form.routeTotalLength" placeholder="请输入路线总长度" />
        </el-form-item>
        <el-form-item label="总时长" prop="routeTotalTime">
          <el-input v-model="form.routeTotalTime" placeholder="请输入路线总时长" />
        </el-form-item>
        <el-form-item label="站点总数" prop="routeTotalSite">
          <el-input v-model="form.routeTotalSite" placeholder="请输入站点总数" />
        </el-form-item>
        <el-form-item label="周末可约">
          <el-radio-group v-model="form.appointHoliday">
            <el-radio
              v-for="dict in appointHolidayList"
              :key="dict.dictValue"
              :label="parseInt(dict.dictValue)"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="路线状态">
          <el-radio-group v-model="form.routeStatus">
            <el-radio
              v-for="dict in routeStatusOptions"
              :key="dict.dictValue"
              :label="parseInt(dict.dictValue)"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="早班时间" prop="startAmTime">
          <el-input v-model="form.startAmTime" placeholder="请输入早班发车时间" />
        </el-form-item>
        <el-form-item label="晚班时间" prop="startPmTime">
          <el-input v-model="form.startPmTime" placeholder="请输入晚班发车时间" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRoute, getRoute, delRoute, addRoute, updateRoute, exportRoute } from "@/api/bus/route";
import { listSite } from "@/api/bus/site";
import { exportRouteSite } from "@/api/bus/routeSite";

export default {
  name: "Route",
  components: {
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedWitRouteSite: [],
      appointHolidayList: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 路线表格数据
      routeList: [],
      // 站点路线表格数据
      witRouteSiteList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 路线状态字典
      routeStatusOptions: [],
      siteList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        routeName: null,
        routeTotalLength: null,
        routeTotalTime: null,
        routeTotalSite: null,
        routeStatus: null,
        startAmTime: null,
        startPmTime: null,
        appointHoliday: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        routeName: [
          { required: true, message: "路线名称不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("sys_normal_disable").then(response => {
      this.routeStatusOptions = response.data;
    });
    this.getDicts("is_appoint_holiday").then(response => {
      this.appointHolidayList = response.data;
    });
    this.getAllSite();
  },
  methods: {
    /** 查询路线列表 */
    getList() {
      this.loading = true;
      listRoute(this.queryParams).then(response => {
        this.routeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getAllSite(){
      listSite().then(res => {
        this.siteList = res.rows;
      })
    },
    // 路线状态字典翻译
    routeStatusFormat(row, column) {
      return this.selectDictLabel(this.routeStatusOptions, row.routeStatus);
    },
    appointHolidayFormat(row, column){
      if(row.appointHoliday == 0){
        return "可以";
      }else {
        return "不可以";
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    handleManage(row) {//站点管理
      const tableId = row.routeId;
      this.$router.push({path:'/route/routeSite',query: {tableId:tableId}})
    },
    // 表单重置
    reset() {
      this.form = {
        routeId: null,
        routeName: null,
        routeTotalLength: null,
        routeTotalTime: null,
        routeTotalSite: null,
        routeStatus: 0,
        startAmTime: null,
        startPmTime: null,
        createTime: null
      };
      this.witRouteSiteList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.routeId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加路线";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const routeId = row.routeId || this.ids
      getRoute(routeId).then(response => {
        this.form = response.data;
        this.witRouteSiteList = response.data.witRouteSiteList;
        this.open = true;
        this.title = "修改路线";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.witRouteSiteList = this.witRouteSiteList;
          if (this.form.routeId != null) {
            updateRoute(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRoute(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handleSortChange(){//站点排序号触发事件,直接对集合内序号重新排序
      this.handleSort();
    },
    handleSort(){
      this.witRouteSiteList.sort((obj1, obj2) => {
        return obj1.sort - obj2.sort;
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const routeIds = row.routeId || this.ids;
      this.$confirm('是否确认删除路线编号为"' + routeIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delRoute(routeIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
	/** 站点路线序号 */
    rowWitRouteSiteIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 站点路线添加按钮操作 */
    handleAddWitRouteSite() {
      let obj = {};
      obj.siteId = "";
      obj.sort = "";
      obj.amArriveTime = "";
      obj.pmArriveTime = "";
      this.witRouteSiteList.push(obj);
    },
    /** 站点路线删除按钮操作 */
    handleDeleteWitRouteSite() {
      if (this.checkedWitRouteSite.length == 0) {
        this.$alert("请先选择要删除的站点路线数据", "提示", { confirmButtonText: "确定", });
      } else {
        this.witRouteSiteList.splice(this.checkedWitRouteSite[0].index - 1, 1);
      }
    },
    /** 单选框选中数据 */
    handleWitRouteSiteSelectionChange(selection) {
      if (selection.length > 1) {
        this.$refs.witRouteSite.clearSelection();
        this.$refs.witRouteSite.toggleRowSelection(selection.pop());
      } else {
        this.checkedWitRouteSite = selection;
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有路线数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportRoute(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    },
    handleAllExport(){
      const queryParams = {};
      this.$confirm('是否确认导出所有站点路线数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return exportRouteSite(queryParams);
      }).then(response => {
        this.download(response.msg);
      })
    }
  }
};
</script>
